// 导入request.js请求工具
import request from '@/utils/request.js'

// 提供调用注册接口的函数
export const userRegisterService = (registerData) => {
  // 借助于urlSearchParams完成传递
  const params = new URLSearchParams()
  for (let key in registerData) {
    params.append(key, registerData[key]);
  }
  return request.post('/user/register', params);
}

// 提供调用登录接口的函数
export const userLoginService = (loginData) => {
  const params = new URLSearchParams()
  for (let key in loginData) {
    params.append(key, loginData[key]);
  }
  return request.post('/user/login', params);
}

// 更新密码
export const updatePwd = (passwordData) => {
  return request.patch('/user/updatePwd', {
    old_pwd: passwordData.oldPassword,  // 将前端的字段名映射到后端要求的字段名
    new_pwd: passwordData.newPassword,
    re_pwd: passwordData.rePassword
  })
}

//用户获取自己详细信息
export const userInfoService = () => {
  return request.get('/user/userInfo')
}

// 获取用户信息
export const userInfoPublicService = (nickname) => {
  return request.get('/user/userInfoPublic?nickname=' + nickname)
}

// 上传
export const uploadFileService = (formData) => {
  return request.post('/upload', formData);
}

//修改头像
export const userAvatarUpdateService = (avatarUrl) => {
  const params = new URLSearchParams();
  params.append('avatarUrl', avatarUrl)
  return request.patch('/user/updateAvatar', params)
}

// 退出登录
export const cleanAuthData = () => {
  // 清理所有认证相关存储
  localStorage.removeItem('token');
  sessionStorage.removeItem('tempData');

  // 如果是Vue/React项目，清理状态管理中的数据
  store.commit('user'); // Vuex示例
};

export const userLogoutService = () => {
  return request.post('/user/logout').finally(() => {
    // 无论如何都执行token清理
    const tokenStore = useTokenStore()
    tokenStore.removeToken()

    // 清理内存残留（安全增强）
    if (window.performance && window.performance.memory) {
      delete window.performance.memory;
    }
  })
}